﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;



namespace SPMigrationOracleUtility
{
    public partial class ExcelSPmigration : Form
    {
        Collect_Site obj1 = new Collect_Site();
        Business objBus = new Business();

        int ListSelectioncnt = 0;
        int Libraryselcount = 0;
        bool srctblchanged = false, desttblchanged = false;
        bool flagMapInit;
        bool flagcgintabl;

        OleDbDataAdapter dataAdapter;
        DataTable dt;
        DataSet dataSet;
        public string excelFileName { get; set; }
        public string SiteUrl = Convert.ToString(SPMigrationOracleUtility.Appl.Default.SiteURL);

        public ExcelSPmigration()
        {
            InitializeComponent();
        }

        private void frm_ExcelSPmigration_Load(object sender, EventArgs e)
        {

            txtUrl.Text = SiteUrl;
            this.Height = 450;
            this.Width = 800;
            objBus.Panel_Prop(pnlMappingInit);
            objBus.Panel_Prop(pnlExcelList);
            objBus.Panel_Prop(pnlSPList);
            objBus.Panel_Prop(pnlMappingFnl);
            objBus.Panel_Prop(pnlIntegrate);
            lblDisp.Text = "Excel and SharePoint Mapping Step-1 - Create Mapping Name";
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
                      
            GetFilePathFields();
            gvExceldata.DataSource = null;
            objBus._pnl2Trans(gvExceldata, btnNextPnl2);
           
  
        }

        public void GetFilePathFields()
        {
            this.openFileDialog1.Dispose();
            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                excelFileName = openFileDialog1.FileName;
                FileHelper objHelper = new FileHelper(excelFileName);
                txtFilePath.Text = "";
                //txtFilePath.Text = objHelper.DirectoryName + "\\" + objHelper.FileName;
                txtFilePath.Text = excelFileName;
                if (objHelper.Extension == ".xlsx" || objHelper.Extension == ".xls")
                {
                   // MessageBox.Show("Valid File Extension Continue the Process");
                    btnReadExcel.Enabled = true;
                }
                else
                {
                    gvExceldata.DataSource = null;
                    MessageBox.Show(excelFileName + ":   Invalid File Extension");
                    btnReadExcel.Enabled = false;
                    objBus._pnl2Trans(gvExceldata, btnNextPnl2);
                }
            }
            else
            { 
            
            }
        }

        private void btnCancelPnl1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnNextPnl1_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-2 - Select SpreadSheet";
            pnlMappingInit.Hide();
            pnlExcelList.Show();            
        }

        

        private void btnPrevPnl2_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-1 - Create Mapping Name";
            pnlMappingInit.Show();
            pnlExcelList.Hide(); 
        }

        private void btnCheckFileType_Click(object sender, EventArgs e)
        {
           
        }

        private void btnReadExcel_Click(object sender, EventArgs e)
        {
                FileHelper objHelper = new FileHelper(excelFileName);
                CmbSrcTableName.Items.Add(objHelper.FileName);
                CmbSrcTableName.SelectedIndex = 0;
                objBus._ExcelData(excelFileName, CmbSrcFieldName, gvExceldata);
                CmbSrcFieldName.SelectedIndex = 0;
                objBus._pnl2Trans(gvExceldata, btnNextPnl2);
        }

        private void btnNextPnl2_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-3 - Select SharePoint List/Library";
            pnlExcelList.Hide();
            pnlSPList.Show();
        }

        private void btnPrevPnl3_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-2 - Select SpreadSheet";
            pnlExcelList.Show();
            pnlSPList.Hide();
        }

        private void btnNextPnl3_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-4 - Excel-SharePoint Mapping Fields";
            pnlMappingFnl.Show();
            pnlSPList.Hide();
            Pnl4_Tranaction();
           
        }

        private void Pnl4_Tranaction()
        {

            ListItemPair li = (ListItemPair)cmbSites.SelectedItem;
            lblDestSiteName.Text = li.URL;

            
         
            if (flagMapInit)
            {
                Map_ck_TblView();
                Map_ck_LstLib();
                if (srctblchanged == true || desttblchanged == true)
                {
                    MappingInit();
                    dg1.DataSource = null;
                    AddTableColumn();
                    srctblchanged = false;
                    desttblchanged = false;
                    flagcgintabl = true;
                }
                else
                {
                    //flagcgintabl = false;
                }
            }
            else
            {
                AddTableColumn();
                MappingInit();
            }

            if (dg1.Rows.Count == 0) { btnNextPnl4.Enabled = false; } else { btnNextPnl4.Enabled = true; }

        }

        public void Map_ck_TblView()
        {
            
            if (!CmbSrcTableName.Items.Contains((FileHelper)CmbSrcTableName.SelectedItem))
                    srctblchanged = true;
        }

        public void Map_ck_LstLib()
        {
            try
            {
                foreach (ListItemPair srctblName in lstMapListLib.Items)
                {
                    if (!CmbDestListName.Items.Contains(srctblName))
                        srctblchanged = true;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            if (lstMapListLib.Items.Count != CmbDestListName.Items.Count)
            {
                desttblchanged = true;
            }

        }

        public void MappingInit()
        {
            CmbDestListName.Items.Clear();
            CmbSrcTableName.Items.Clear();

            CmbDestListName.DisplayMember = "Text";
            foreach (object obj in lstMapListLib.Items)
            {
                CmbDestListName.Items.Add(obj);

            }
            if (CmbDestListName.Items.Count > 0)
                CmbDestListName.SelectedIndex = 0;

            CmbSrcTableName.DisplayMember = "FileName";
            CmbSrcTableName.Items.Add(new FileHelper(excelFileName));
           
            if (CmbSrcTableName.Items.Count > 0)
                CmbSrcTableName.SelectedIndex = 0;
        }

        public void AddTableColumn()
        {
            dt = new DataTable();
            dt.Columns.Add("SourceTableName", typeof(string));
            dt.Columns.Add("SourceTableColumn", typeof(string));
            dt.Columns.Add("SourceColumnType", typeof(string));
            dt.Columns.Add("DestinationListName", typeof(string));
            dt.Columns.Add("DestinationListColumn", typeof(string));
            dt.Columns.Add("DestinationColumnType", typeof(string));
            dt.Columns.Add("DestinationListTemplate", typeof(string));
            dg1.DataSource = dt;
        }
        

        private void btnPrevPnl4_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-3 - Select SharePoint List/Library";
            flagMapInit = true;
            pnlMappingFnl.Hide();
            pnlSPList.Show();
        }

        private void CmbSrcFieldName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ExcelItemPairs objType = (ExcelItemPairs)CmbSrcFieldName.SelectedItem;
            lblSrcFieldName.Text = objType.Type;
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            cmbSites.Items.Clear();
            obj1.GetSubSites(cmbSites, txtUrl.Text);
            if (cmbSites.Items.Count > 0)
            {
                cmbSites.SelectedIndex = 0;
            }
        }

        private void cmbSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListItemPair oweb = (ListItemPair)cmbSites.SelectedItem;
            obj1.GetLists(lstLibList, cmbSites, oweb.URL);
            clr_MapList();
        }

        private void clr_MapList()
        {
            lstMapListLib.Items.Clear();
            ListSelectioncnt = 0;
            Libraryselcount = 0;
            Step4Enable();

            if (lstLibList.Items.Count > 0)
            {
                btnListLibAdd.Enabled = true;
            }
            else
            {
                btnListLibAdd.Enabled = false;
            }

        }

        public void Step4Enable()
        {
            if (ListSelectioncnt > 0 || Libraryselcount > 0)
            {
                btnNextPnl3.Enabled = true;
                btnListLibRem.Enabled = true;
            }
            else
            {
                btnListLibAdd.Enabled = true;
                btnNextPnl3.Enabled = false;
                btnListLibRem.Enabled = false;
            }
        }

        private void btnListLibAdd_Click(object sender, EventArgs e)
        {
            if (lstLibList.Text == "")
                MessageBox.Show("Please Select List / Library");
            else
                MoveData(lstLibList, lstMapListLib, 1);
        }

        private void btnListLibRem_Click(object sender, EventArgs e)
        {
            MoveData(lstMapListLib, lstLibList, -1);
        }

        public void MoveData(ListBox objListsrc, ListBox objListDest, int val)
        {

            bool adddata1 = false;
            string type1 = "";

            try
            {
                ListItemPair objList = (ListItemPair)objListsrc.SelectedItem;
                if (objList.ListTemplate == Microsoft.SharePoint.Client.BaseType.DocumentLibrary)
                {
                    Libraryselcount = Libraryselcount + val;
                }
                else
                {
                    ListSelectioncnt = ListSelectioncnt + val;
                }

                if (ListSelectioncnt == 0 && Libraryselcount == 1)
                {
                    adddata1 = true;
                    btnListLibAdd.Enabled = true;

                }
                else if (ListSelectioncnt == 1 && Libraryselcount == 0)
                {

                    adddata1 = true;
                    btnListLibAdd.Enabled = true;

                }
                else if (ListSelectioncnt == 2 && Libraryselcount == 0)
                {
                    adddata1 = true;
                    btnListLibAdd.Enabled = false;

                }
                else if (ListSelectioncnt == 1 && Libraryselcount == 1)
                {
                    adddata1 = true;
                    btnListLibAdd.Enabled = false;
                }
                else if (ListSelectioncnt == 0 && Libraryselcount == 0)
                {
                    adddata1 = true;
                    // btnListLibRem.Enabled = false;
                }
                else
                {
                    Libraryselcount = 1;
                    MessageBox.Show("Invalid Mapping.");
                }

                if (adddata1)
                {
                    objListDest.Items.Add(objList);
                    objListDest.DisplayMember = "Text";
                    int selectedIndex = Convert.ToInt32(objListsrc.SelectedIndex);
                    objListsrc.Items.RemoveAt(selectedIndex);
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show("Select the valid List or Library");
            }


            Step4Enable();
        }

        private void CmbDestListName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListItemPair oweb = (ListItemPair)CmbDestListName.SelectedItem;
            obj1.GetListFields(CmbDestListName, CmbDestFieldName, oweb.URL);
        }

        private void CmbDestFieldName_SelectedIndexChanged(object sender, EventArgs e)
        {
            obj1.GetListFieldType(CmbDestFieldName, lblDestFieldName);
        }

       
        private void btnAddGrid_Click(object sender, EventArgs e)
        {
            bool exist = false;

            ExcelItemPairs objsrc = (ExcelItemPairs)CmbSrcFieldName.SelectedItem;
            ListItemPair dispName = (ListItemPair)CmbDestListName.SelectedItem;
            DestFieldType intName = (DestFieldType)CmbDestFieldName.SelectedItem;

            foreach (DataRow row in dt.Rows)
            {
                if (Convert.ToString(row["SourceTableName"]) == Convert.ToString(objsrc.SrcName)
                    && Convert.ToString(row["SourceTableColumn"]) == Convert.ToString(objsrc.Value ) 
                    && Convert.ToString(row["SourceColumnType"]) == Convert.ToString(lblSrcFieldName.Text) 
                    && Convert.ToString(row["DestinationListName"]) == Convert.ToString(dispName.Text) 
                    && Convert.ToString(row["DestinationListColumn"]) == Convert.ToString(intName.internalName) 
                    && Convert.ToString(row["DestinationColumnType"]) == Convert.ToString(lblDestFieldName.Text)
                    && Convert.ToString(row["DestinationListTemplate"]) == Convert.ToString(dispName.ListTemplate))
               
                {
                    MessageBox.Show("Duplicate Entry ! Same entry exists ","Duplication",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                    exist = true;
                }

                else if (Convert.ToString(row["DestinationListName"]) == Convert.ToString(dispName.Text) && Convert.ToString(row["DestinationListColumn"]) == Convert.ToString(intName.internalName))
                   
                {
                    MessageBox.Show("Cannot map Destination List Field twice" + System.Environment.NewLine + "'" + row["DestinationListColumn"] + "'  Field already mapped", "Mapping Exist Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    exist = true;
                }
            }

            if (!exist)
            {
                if (string.Equals(lblDestFieldName.Text, "File", StringComparison.CurrentCultureIgnoreCase))
                {
                    DialogResult result = MessageBox.Show("Could you please ensure Source Table field '" + objsrc.SrcName + "' consist URL(Document Path). Since you have selected Document Libray", "Document Library Verification", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (result == DialogResult.OK)
                    {
                        dt.Rows.Add(objsrc.SrcName, objsrc.Value, lblSrcFieldName.Text, dispName.Text, intName.internalName, lblDestFieldName.Text, Convert.ToString(dispName.ListTemplate));
                        dg1.DataSource = dt;
                    }
                }
                else
                {
                    dt.Rows.Add(objsrc.SrcName, objsrc.Value, lblSrcFieldName.Text, dispName.Text, intName.internalName, lblDestFieldName.Text, Convert.ToString(dispName.ListTemplate));
                    dg1.DataSource = dt;
                }
            }
            if (dg1.Visible)
            {
                btnNextPnl4.Enabled = true;
            }
            

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
               // FileHelper objHelper = new FileHelper(excelFileName);
                Mapping_List objMap = new Mapping_List(txtMappingName.Text, txtMappingDesc.Text, "","", "",excelFileName );
                objMap.MapList(dt, lblDestSiteName.Text, txtMappingName.Text);
                MessageBox.Show("Mapping Created");
                this.Close();
         }

        private void btnNextPnl4_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-5 - Excel-SharePoint Mapping Details";
            pnlIntegrate.Show();
            pnlMappingFnl.Hide();
            MappingDetails();
        }

        private void btnPrevPnl5_Click(object sender, EventArgs e)
        {
            lblDisp.Text = "Excel and SharePoint Mapping Step-4 - Excel-SharePoint Mapping Fields";
            pnlIntegrate.Hide();
            pnlMappingFnl.Show();
        }

        private void btnCancelPnl5_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCancelPnl4_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCancelPnl3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnCancelPnl2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void MappingDetails()
        {
                lblMapName.Text = txtMappingName.Text.ToUpper();
                lblMapDesc.Text = txtMappingDesc.Text.ToUpper();
                lblSrcTblView.Text = "";

                ExcelItemPairs objType = (ExcelItemPairs)CmbSrcFieldName.SelectedItem;
                lblSrcTblView.Text = objType.SrcName;

                lblDestListLib.Text = "";
                foreach (ListItemPair destListName in lstMapListLib.Items)
                {
                    string s1 = destListName.Text.ToUpper();
                    lblDestListLib.Text = lblDestListLib.Text.ToUpper() +System.Environment.NewLine + s1.ToString();
                }
                lblMapRowCnt.Text = Convert.ToString(dg1.Rows.Count);
                lblSrcRecCnt.Text = Convert.ToString(gvExceldata.Rows.Count);

        }

        private void pnlMappingInit_MouseMove(object sender, MouseEventArgs e)
        {
            if (txtMappingName.Text == "")
            {
                btnNextPnl1.Enabled = false;
            }
            else
            {
                btnNextPnl1.Enabled = true;
            }
        }

        private void txtMappingName_Leave(object sender, EventArgs e)
        {
            if (txtMappingName.Text == "")
            {
                btnNextPnl1.Enabled = false;
            }
            else
            {
                btnNextPnl1.Enabled = true;
            }
        }

        private void deleteSelectedRowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to Delete the Selected Row ?", "Row Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                dg1.Rows.Remove(dg1.CurrentRow);
            }
            if (dg1.Rows.Count == 0) { btnNextPnl4.Enabled = false; } else { btnNextPnl4.Enabled = true; }
        }

        private void dg1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (dg1.Rows.Count > 0)
                {
                    contextMenuStrip1.Show(Cursor.Position);
                }
            }
        }

      }

 }

